
#include "taglibWrapper.h"


extern "C"
JNIEXPORT jstring JNICALL
Java_com_lalilu_lmedia_wrapper_Taglib_getLyric(JNIEnv *env, jobject thiz, jstring file_path) {
    const char *file_path_c = env->GetStringUTFChars(file_path, nullptr);
    TagLib::FileRef fileRef(file_path_c);

    if (fileRef.isNull()) {
        return env->NewStringUTF("File is not supported");
    }

    auto map = fileRef.tag()->properties();

    auto lyrics = map["LYRICS"];
    if (lyrics.size() > 0 && lyrics[0].size() > 0) {
        return env->NewStringUTF(lyrics[0].toCString(true));
    }
    return nullptr;
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_lalilu_lmedia_wrapper_Taglib_writeLyricInto(JNIEnv *env, jobject thiz, jstring file_path,
                                                     jstring lyric) {
    auto filePathStr = env->GetStringUTFChars(file_path, nullptr);
    auto lyricStr = env->GetStringUTFChars(lyric, nullptr);

    TagLib::FileRef fileRef(filePathStr);
    if (fileRef.isNull()) return JNI_FALSE;

    auto map = fileRef.file()->properties();
    map.replace("LYRICS", TagLib::String(lyricStr, TagLib::String::Type::UTF8));
    fileRef.file()->setProperties(map);

    return fileRef.file()->save() ? JNI_TRUE : JNI_FALSE;
}